﻿/**
 * ImageHolder
 *
 * ImageHolder loads an image, and lets ImageHandler object move, rotate or resize the image loaded.
 *
 * ImageHolder is part of the sample application for the presentation on Flash ActionScript Cafe's 2nd conference.
 * 
 *
 * @author: Han Sanghun (http://hangunsworld.com, hanguns@gmail.com)
 * @created: 2007 04 00
 * @last modified: 2008 05 24
 */

package conf{
	
	import flash.display.*;
	import flash.events.*;
	import flash.geom.*;
	import flash.net.*;
	import flash.system.LoaderContext;
	import flash.ui.*;
	
	import mx.controls.Alert;
	
	import vo.voImgInfo;
	
	
	public class ImageHolder extends MovieClip{
		
		private var _root:MovieClip;
		private var _parent:Sprite;
		
		public var path:String;
		
		// 로더
		public var loader:Loader = new Loader();
		public var image:Bitmap;
		private var loaderUR:URLRequest;
		
		private var context:LoaderContext;
		
		
		// 원본 이미지
		private var origin_bd:BitmapData;
		// 사본 이미지
		public var view_bd:BitmapData;
		private var view_bmp:Bitmap;
		
		// 이미지 크기
		public var originWidth:Number;
		public var originHeight:Number;
		public var minWidth:Number = 20;
		public var minHeight:Number = 20;
		public var maxWidth:Number = Number.POSITIVE_INFINITY;
		public var maxHeight:Number = Number.POSITIVE_INFINITY;
		private const MAX_WIDTH:uint = 490;
		private const MAX_HEIGHT:uint = 740;
		
		
		private var cm:ContextMenu;
		
		public var _ie:ImageEditor;
		
		public var _oSelectedObj:voImgInfo;
		/**
		 * Constructor function.
		 *
		 * @param pSrc 이미지 경로
		 */
		public function ImageHolder(pSrc:String, ie:ImageEditor, oSelectedObj:voImgInfo=null){
		//public function ImageHolder(pSrc:String){
			_oSelectedObj = oSelectedObj;
			_ie = ie;
			path = pSrc;
			
			// 로더
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
			loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, imageLoading);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, imageLoadError);
			
			loaderUR = new URLRequest();
			
			// 로더 컨텍스트
			context = new LoaderContext();
			context.checkPolicyFile = true;
			
			
			addEventListener(Event.ADDED_TO_STAGE, addedListener);
			
		}// end constructor
		
		
		/**
		 * 스테이지에 애드되면, 초기화 실행
		 */
		private function addedListener(evt:Event):void{
			
			removeEventListener(Event.ADDED_TO_STAGE, addedListener);
			
			_root = _ie;
			_parent = parent as Sprite;
			
			
			// 이미지 로드
			loaderUR.url = cfv.SERVER_PATH+path;
			loader.load(loaderUR, context);
			
			
			// 컨텍스트 메뉴 설정
			cm = new ContextMenu();
			cm.hideBuiltInItems();
			
			var cmi:ContextMenuItem;
			cmi = new ContextMenuItem(" + Bring to Front(image holder)");
			cmi.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, cmiListener);
			cm.customItems.push(cmi);
			
			cmi = new ContextMenuItem(" + Bring Forward");
			cmi.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, cmiListener);
			cm.customItems.push(cmi);
			
			cmi = new ContextMenuItem(" + Send Backward");
			cmi.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, cmiListener);
			cm.customItems.push(cmi);
			
			cmi = new ContextMenuItem(" + Send to Back");
			cmi.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, cmiListener);
			cm.customItems.push(cmi);
			
			cmi = new ContextMenuItem(" + Select", true);
			cmi.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, cmiListener);
			cm.customItems.push(cmi);
			
			cmi = new ContextMenuItem(" + Reset", true);
			cmi.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, cmiListener);
			cm.customItems.push(cmi);
			
			cmi = new ContextMenuItem(" + Remove");
			cmi.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, cmiListener);
			cm.customItems.push(cmi);
			
			contextMenu = cm;
			
		}// end addedListener
		
		
		/**
		 * 컨텍스트 메뉴 선택 이벤트리스너.
		 */
		private function cmiListener(e:ContextMenuEvent):void{
			
			var cmi:ContextMenuItem = e.target as ContextMenuItem;
			var str:String = cmi.caption;
			
			
			switch(str){
				
				case " + Bring to Front":
					_parent.setChildIndex(this, _parent.numChildren - 1);
					break;
				
				case " + Bring Forward":
					_parent.setChildIndex(this, _parent.getChildIndex(this) + 1);
					break
				
				case " + Send Backward":
					var aa:int = _parent.getChildIndex(this);
					if(aa <= 0) {
						return;
					}
					_parent.setChildIndex(this, aa - 1);
					break;
				
				case " + Send to Back":
					_parent.setChildIndex(this, 0);
					break;
				
				case " + Select":
					_root.handler.setTarget(this);
					break;
				
				case " + Reset":
					resetImage();
					break;
				
				case " + Remove":
					_parent.removeChild(this);
					break;
				
			}// end switch
			
		}// end cmListener
		
		/******************************************************************************************************
		                                                       이미지 로드 관련 이벤트
		******************************************************************************************************/
		/**
		 * 이미지를 로드하기
		 *
		 * @param pSrc: 이미지 경로
		 */
		public function loadImage(pSrc:String, pWid:uint=0, pHgt:uint=0):void{
			 
			loaderUR.url = pSrc;
			loader.load(loaderUR, context);
			
		}// end loadImage
		
		
		
		/**
		 * 이미지 로드 완료 이벤트
		 */
		private function imageLoaded(evt:Event):void{
			
			//_root.hideMessage();
			
			var bigImage:Boolean = false;
			
			
			var w:uint = loader.width;
			var h:uint = loader.height;
			
			// 2880 픽셀 이상이면 리사이즈 하기
			if(w > 2880 || h > 2880){
				
				bigImage = true;
				
				loader.width = 2880;
				loader.height = 2880;
				
				var scale:Number = Math.min(loader.scaleX, loader.scaleY);
				loader.scaleX = scale;
				loader.scaleY = scale;
				
				w = loader.width;
				h = loader.height;
			}
			
			
			// 원본 비트맵데이터
			var bd:BitmapData = new BitmapData(w, h, true, 0);
			bd.draw(loader);
			var img:Bitmap = new Bitmap(bd);
			
			
			originWidth = img.width;
			originHeight = img.height;
			
			
			// 사본 비트맵데이터 생성
			if(view_bd != null){
				view_bd.dispose();
			}// end if
			view_bd = new BitmapData(originWidth, originHeight, true, 0);
			view_bd.draw(img, null, null, null, null, true);
			
			
			// 사본을 이용해서 비트맵 생성
			if(view_bmp == null){
				view_bmp = new Bitmap(view_bd, "auto", true);
				addChild(view_bmp);
			}else{
				view_bmp.bitmapData = view_bd;
			}
			
			image = view_bmp;
			
			
			// 왼쪽 list클릭시 저장되어있는 data로드.

			resetImage(); // 실제 여기서 기존 데이터 로딩함..
			
			ImageEditor(_root).handler.setTarget(this);
			
			visible = true;
			
			
			if(bigImage){
				// 2880 픽셀 이상이면, 메세지 표시
				Alert.show("The image is larger than 2880 pixels.\rThe Image is resized.");
			}
			
			
			removeEventListener(MouseEvent.CLICK, clickListener);
			addEventListener(MouseEvent.CLICK, clickListener);
			

			
		}// end imageLoaded
		
		
		
		/**
		 * 로딩중 프로그래스 표시
		 */
		private function imageLoading(e:ProgressEvent):void{
			//Alert.show("Image loading. " + uint(e.bytesLoaded / e.bytesTotal * 100) + "%");
			
		}// end imageLoading
		
		/**
		 * 로딩 중 IO 에러 발생
		 */
		private function imageLoadError(evt:IOErrorEvent):void{
			
			Alert.show("Can not load the image\rbecause of an IOError.");
			
		}// end imageLoadError
		/******************************************************************************************************
		                                                       이미지 로드 관련 이벤트
		******************************************************************************************************/

		
		
		/**
		 * 이미지 크기, 회전 초기화
		 */
		public function resetImage():void{
			
			
			rotation = 0;
			
			view_bmp.scaleX = view_bmp.scaleY = 1;
			
			
			if(_oSelectedObj != null) {
				x 			= _oSelectedObj.iPosX;
				y 			= _oSelectedObj.iPosY;
				
				//width 	= _oSelectedObj.iWidth;
				//height 	= _oSelectedObj.iHeight; 
				
				image.width 	= _oSelectedObj.iWidth;
				image.height 	=  _oSelectedObj.iHeight;
				
				rotation = _oSelectedObj.iRotate;
				
				image.width 	= _oSelectedObj.iWidth;
				image.height 	=  _oSelectedObj.iHeight;
				
//				image.rotation = _oSelectedObj.iRotate;
//				_root.handler.mc.roation = _oSelectedObj.iRotate;
				
				//view_bmp.width 		= _oSelectedObj.iWidth;
				//view_bmp.height 	= _oSelectedObj.iHeight;
				
				//view_bmp.scaleX = view_bmp.scaleY = 1;				
				
			} 
			// 기존 코드 
			else {
				// 크기 초기화
				if(view_bmp.width > MAX_WIDTH){
					view_bmp.width = MAX_WIDTH;
				}
				if(view_bmp.height > MAX_HEIGHT){
					view_bmp.height = MAX_HEIGHT;
				}
				
				view_bmp.scaleX = view_bmp.scaleY = Math.min(view_bmp.scaleX, view_bmp.scaleY);
			}
			
			//view_bmp.scaleX = view_bmp.scaleY = Math.min(view_bmp.scaleX, view_bmp.scaleY);
			
			view_bmp.x = -view_bmp.width/2;
			view_bmp.y = -view_bmp.height/2;
			
			
			
			
			//view_bmp.smoothing = true;
		}// end resetImage
		
		
		/**
		 * 이미지 클릭하면 ImageHandler의 타겟 설정
		 */
		private function clickListener(e:MouseEvent):void{
			
			_root.handler.setTarget(this);
			
		}// end clickListener
		
		
	}// end class
}// end package